package com.abraxascorp.resources;

import java.io.IOException;

import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.abraxascorp.managers.JDOManager;
import com.abraxascorp.model.Location;
import com.abraxascorp.responses.LocationAddResponse;
import com.google.gson.Gson;

@Path("/location")
public class LocationResource {

	private static final Gson gson = new Gson();
	private static final JDOManager<Location> jdoManager = new JDOManager<Location>();
	
	@Path("/add")
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.TEXT_PLAIN)
    public String addLocation(MimeMultipart form) throws SecurityException, NoSuchFieldException, MessagingException, IOException {
		int bodyPartCount = form.getCount();
		
		for(int bodyPartIndex=0; bodyPartIndex<bodyPartCount; bodyPartIndex++) {
			BodyPart bodyPart = form.getBodyPart(bodyPartIndex);
			String disposition = bodyPart.getHeader("Content-Disposition")[0];
			
			if(disposition.contains("name=\"contact\""))
				System.out.println("Contact: " +bodyPart.getContent());
			else if(disposition.contains("name=\"photo\""))
				System.out.println("Photo: " +bodyPart.getContent());
			else if(disposition.contains("name=\"description\""))
				System.out.println("Description: " +bodyPart.getContent());
			else if(disposition.contains("name=\"location\""))
				System.out.println("Location: " +bodyPart.getContent());
		}
		
		//BodyPart bodyPart = photo.getBodyPart(0);
		LocationAddResponse response = new LocationAddResponse();
		
		/*if(contact.isEmpty()) {
			response.setError("No contact entered");
			return gson.toJson(response);
		}*/
		/*if(latitude.isEmpty() || longitude.isEmpty()) {
			response.setError("No location entered");
			return gson.toJson(response);
		}
		
		GeoPt locationToAddGeoPt = new GeoPt(Float.valueOf(latitude), Float.valueOf(latitude));
		Location locationToAdd = new Location(contact, profilePicUrl, locationToAddGeoPt, description);
		if(!jdoManager.findObjectsWithField("location", locationToAdd.getLocation(), Location.class).isEmpty()) {
			response.setError("Infomation already exists for this location");
			return gson.toJson(response);
		}
		
		response.setSuccess(jdoManager.persist(locationToAdd));*/
		
		return gson.toJson(response);
	}
}
